package com.ruoyi.business.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.business.domain.MroLogistics;
import com.ruoyi.business.service.IMroLogisticsService;
import com.ruoyi.business.utils.CategoryUtil;
import com.ruoyi.business.utils.MyException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDictDataMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
public class LogisticsInfoExcelListener extends AnalysisEventListener<Map<Integer, String>> {
    @Autowired
    private IMroLogisticsService mroLogisticsService;

    @Autowired
    private CategoryUtil categoryUtil;

    // @Autowired
    // private RedisCache redisCache;

    // @Autowired
    //private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    public List<String> errorList = new ArrayList<>();
    private final List<MroLogistics> saveList = new ArrayList<>();

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");


    public LogisticsInfoExcelListener(IMroLogisticsService mroLogisticsService) {
        this.mroLogisticsService = mroLogisticsService;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        int currentRowNum = context.readRowHolder().getRowIndex() + 1;
        log.info("第{}行解析数据: {}", currentRowNum, JSONUtil.toJsonStr(data));
        try {
            saveList.add(parseRowToLogisticsInfo(data, currentRowNum));
        } catch (Exception e) {
            log.error("第{}行解析异常：{}", currentRowNum, e.getMessage(), e);
            errorList.add(String.format("第%s行错误：%s", currentRowNum, e.getMessage()));
        }
    }


    private MroLogistics parseRowToLogisticsInfo(Map<Integer, String> data, int rowNum) throws Exception {
        List<String> list = new ArrayList<>();
        for (int i = 0; i <= 30; i++) {
            String val = data.get(i);
            list.add(val != null ? val.trim() : "");
        }
        MroLogistics info = new MroLogistics();
        if (StringUtils.isEmpty(list.get(0))) {
            throw new MyException("微盟订单编号为空");
        }
        if (StringUtils.isEmpty(list.get(1))) {
            throw new MyException("代客订单编号为空");
        }
        if (StringUtils.isEmpty(list.get(2))) {
            throw new MyException("物流名称为空");
        }
        if (StringUtils.isEmpty(list.get(3))) {
            throw new MyException("快递单号为空");
        }

        //微盟合同号
        String orderNo = list.get(0).trim();
        //代客订单编号dkId
        String outerOrderNo = list.get(1).trim();
        //物流名称
        String companyName = list.get(2).trim();
        //快递单号
        String number = list.get(3).trim();
        // 从Redis获取字典缓存
       /* List<SysDictData> dictDatas = redisCache.getCacheList(DictUtils.getCacheKey("sys_logistics_company"));
        if (dictDatas == null) {
            // 如果缓存不存在，从数据库查询
            dictDatas = sysDictDataMapper.selectDictDataByType("sys_logistics_company");
        }
        boolean b = dictDatas.stream()
                .anyMatch(dictData -> dictData.getDictLabel().equals(companyName));
        if (b == false) {
            throw new MyException("微盟没有该物流,请输入正确的物流名称");
        }*/

        String sys_logistics_company = DictUtils.getDictValue("sys_logistics_company", companyName, null);
        if (StringUtils.isEmpty(sys_logistics_company)) {
            throw new MyException("物流公司[" + companyName + "]不存在");
        }
        info.setOuterOrderNo(outerOrderNo);
        info.setOrderNo(Long.parseLong(orderNo));
        info.setNumber(number);
        String companyNameValue = DictUtils.getDictValue("sys_logistics_company", companyName);

        info.setCompanyName(companyNameValue);
        return info;
    }

    private String getCacheKey(String dictType) {
        return "sys_dict:" + dictType;
    }

    private Date parseDate(String dateStr) throws ParseException {
        return StrUtil.isNotBlank(dateStr) ? new Timestamp(SDF.parse(dateStr).getTime()) : null;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollUtil.isEmpty(saveList)) {
            return;
        }
        if (CollUtil.isNotEmpty(errorList)) {
            return;
        }
        try {
            log.info("共{}条数据，开始入库", saveList.size());
            mroLogisticsService.batchInsertOrUpdateByImport(saveList);
            log.info("入库成功！");
        } catch (Exception e) {
            log.error("数据入库异常：{}", e.getMessage(), e);
            errorList.add("数据入库异常：" + e.getMessage());
        }
    }

}
